#include <stdio.h>
#include "../inc/uthash.h"

typedef struct {
    int id;
} UserItem;

typedef struct {
    UserItem *u;
    UT_hash_handle hh;
} User;

User *g_userList = NULL;

UserItem *NewItem(const int id)
{
    UserItem *item = (UserItem *)malloc(sizeof(UserItem));
    memset(item, 0, sizeof(UserItem));
    item->id = id;
    return item;
}

void AddUser(UserItem *u)
{
    User *tmp = NULL;
    HASH_FIND_PTR(g_userList, &u, tmp);
    if (tmp == NULL) {
        tmp = (User *)malloc(sizeof(User));
        tmp->u = u;
        HASH_ADD_PTR(g_userList, u, tmp);
        printf("Add: %d\n", tmp->u->id);
    } else {
        printf("ADD: %d, exist\n", tmp->u->id);
    }
}

void PrintList()
{
    User *el = NULL;
    User *tmp = NULL;
    printf("Print cnt: %d\n", HASH_COUNT(g_userList));
    HASH_ITER(hh, g_userList, el, tmp)
    {
        printf("Print : %d\n", el->u->id);
    }
}

void FreeList()
{
    User *el = NULL;
    User *tmp = NULL;
    printf("Delete cnt: %d\n", HASH_COUNT(g_userList));
    HASH_ITER(hh, g_userList, el, tmp)
    {
        printf("Print : %d\n", el->u->id);
        HASH_DEL(g_userList, el);
        free(el->u);
        free(el);
    }
}

int main()
{
    AddUser(NewItem(3));
    AddUser(NewItem(13));
    PrintList();
    FreeList();
    PrintList();
    return 0;
}